<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">-->
    <title>批量转换Base64图片</title>
    <style>
        textarea {
            width: 350px;
            height: 200px;
            overflow-y: hidden;
            box-sizing: border-box;
        }

        .item-result {
            padding: 10px;
            display: inline-block;
        }

        .item-result > textarea {
            display: block;
            width: 100%;
            height: 20%;
            margin: 0;
        }

        .tip-wrap {
            display: block;
            position: relative;
            text-align: center;
        }

        .tip-wrap > img {
            /*css会压缩base64图片，保存时非原图*/
            max-width: 200px;
        }

        .tip-wrap > p {
            display: none;
            position: absolute;
            z-index: 999;
            word-break: break-all;
            margin: 0;
        }

        .tip-wrap:hover > p {
            display: block;
            position: absolute;
            border-radius: 2px;
            top: 50%;
            transform: translate(0, -50%);
            background: rgba(0, 0, 0, 0.6);
            padding: 4px;
            color: floralwhite;
        }

    </style>
</head>
<body>
<div style="width: 800px;margin: 0 auto">
    <div style="display: inline-block">

        <div style="border: 1px solid #fafafa">
            <textarea id="elUrlList" placeholder="换行分隔"></textarea>
        </div>
        <button onclick="coverToBase64(event)">转为base64</button>
    </div>
    <div style="display: inline-block;">
        <div style="border: 1px solid #fafafa">
            <textarea id="elBase64Result" placeholder="换行分隔"></textarea>
        </div>
        <input onchange="readUploadImgs(event)" type="file"></input>
        <button onclick="backImgs(event)">base64图片预览</button>
    </div>
    <div id="elResultList">

    </div>

    <script>
        var elUrlList = document.getElementById("elUrlList");
        var elBase64List = document.getElementById("elBase64Result");
        var elResultList = document.getElementById("elResultList");

        function getUrlList() {
            return elUrlList.value.trim().split("\n");
        }

        var resultList = [];

        async function coverToBase64(event) {
            if (!elUrlList.value.trim()) {
                return;
            }
            var urlList = getUrlList();
            elResultList.innerHTML = "";

            for (let i = 0; i < urlList.length; i++) {
                if (!urlList[i]) {
                    continue;
                }
                await getBase64ByXhr(urlList[i]).then(function (res) {
                    // elBase64List.innerText += (res + "\n");
                    var div = document.createElement("div");
                    div.className = "item-result";
                    var a = document.createElement("a");
                    a.className = "tip-wrap";
                    var img = document.createElement("img");
                    img.src = res.data;
                    var p = document.createElement("p");
                    p.innerText = res.url;

                    var textArea = document.createElement("textarea");
                    textArea.value = res.data;

                    a.appendChild(img);
                    a.appendChild(p);

                    div.appendChild(a);
                    div.appendChild(textArea);
                    elResultList.appendChild(div);

                });
            }


        }


        function getBase64ByCanvas() {
            let img = new Image();
            img.setAttribute("crossOrigin", "*");
            img.src = urlList[i];
            img.onload = function (e) {
                console.log(e);
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, img.width, img.height);
                var base64 = canvas.toDataURL();
                // console.log(base64);
            }
        }

        //服务器不支持跨域时，拿不到图片。
        function getBase64ByXhr(imgUrl) {
            return new Promise(function (resolve, reject) {

                var xhr = new XMLHttpRequest();
                xhr.open("get", imgUrl, true);//发起异步请求。同步请求被废弃了
                // 至关重要
                xhr.responseType = "blob";
                xhr.onload = function () {
                    if (this.status == 200) {//跨域返回的也可以是200，服务器已经正确响应，但浏览器拒绝给出。
                        //得到一个blob对象
                        var blob = this.response;
                        let oFileReader = new FileReader();
                        oFileReader.readAsDataURL(blob);
                        oFileReader.onloadend = function (e) {
                            let base64 = e.target.result;
                            // console.log(e);
                            resolve({url: imgUrl, data: base64});
                        }
                        oFileReader.onerror = function (e) {
                            // console.log(e);
                            resolve({url: imgUrl});
                        }
                    }
                    else {
                        resolve({url: imgUrl});
                    }
                }

                try {
                    xhr.send();
                }
                catch (e) {//断网或其他错误
                    reject({url: imgUrl, code: -1});
                }

            });
        }


        function getBase64List() {
            return elBase64List.value.trim().split("\n");
        }

        function backImgs(event) {
            var base64List = getBase64List();
            elResultList.innerHTML = "";

            for (var i = 0; i < base64List.length; i++) {

                var div = document.createElement("div");
                div.className = "item-result";
                var img = document.createElement("img");
                img.src = base64List[i];
                var textArea = document.createElement("textarea");
                textArea.value = base64List[i];

                div.appendChild(img);
                div.appendChild(textArea);

                elResultList.appendChild(div);
            }

        }

        function readUploadImgs(e) {
            var file = e.target.files[0];
            var reader = new FileReader();
            reader.onload = function (e) {
                var result = e.target.result;
                elBase64List.value += (result+"\n");
            };
            reader.readAsDataURL(file);

        }
    </script>

</div>
</body>
</html>